package com.linck.im.dao.mongo;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoCollection;
import lombok.extern.slf4j.Slf4j;
import org.bson.Document;

import java.util.ArrayList;
import java.util.List;

/**
 * mongodb连接工具
 *
 * @author: linck
 * @create: 2021-01-30
 */
@Slf4j
public class MongoDBUtil {

    public static final MongoClient clint;

    static {
        List<ServerAddress> adds = new ArrayList<>();
        // ServerAddress()两个参数分别为 服务器地址 和 端口
        ServerAddress serverAddress = new ServerAddress("127.0.0.1", 27017);
        adds.add(serverAddress);

        // MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
        MongoCredential mongoCredential = MongoCredential.createScramSha1Credential("java", "im", "123456".toCharArray());

        MongoClientOptions options = MongoClientOptions.builder()
                //设置连接超时时间为10s
                .connectTimeout(1000 * 10)
                //设置最长等待时间为10s
                .maxWaitTime(1000 * 10)
                .build();

        clint = new MongoClient(adds, mongoCredential, options);
        log.info("mongodb连接成功");
    }

    public static MongoCollection<Document> getMessageCollection() {
        return clint.getDatabase("im").getCollection("message");
    }

    private MongoDBUtil() {
    }
}
